<?php

namespace App\Http\Requests;

use App\Http\Requests\Traits\ValidateMessage;
use App\Models\Merchant;
use App\Models\Order;
use Illuminate\Foundation\Http\FormRequest;

class EpayOrderRequest extends FormRequest
{
    use ValidateMessage;
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'pid'          => ['required', 'exists:merchants,client_id'],
            'type'         => ['required', 'in:' . implode(',', array_keys(Order::$gatewayMap))],
            'out_trade_no' => ['required'],
            'notify_url'   => ['required', 'url'],
            'return_url'   => ['required', 'url'],
            'name'         => ['required'],
            'money'        => ['required', 'numeric'],
            'sign'         => [
                'required',
                function ($attribute, $value, $fail) {
                    $params = $this->all();
                    $key = Merchant::query()->where('client_id', $params['pid'])->select('client_secret')->firstOrFail();
                    if ($params['sign'] !== epay_sign($params, $key->client_secret) && app()->getLocale() !== 'local') {
                        $fail('签名错误');
                    }
                }
            ],
            'sign_type'    => ['in:md5,MD5'],
        ];
    }

    public function messages()
    {
        return [
            'pid.required'              => '缺少PID参数',
            'pid.exists'                => '当前商户不存在',
            'type.required'             => '缺少type参数',
            'type.in'                   => '支付方式不存在',
            'out_trade_no.required'     => '缺少out_trade_no参数',
            'notify_url.required'       => '缺少notify_url参数',
            'notify_url.url'            => 'notify_url参数必须为url地址',
            'return_url.required'       => '缺少return_url参数',
            'return_url.url'            => 'return_url参数必须为url地址',
            'name.required'             => '缺少name参数',
            'money.required'            => '缺少money参数',
            'money.numeric'             => '金额输入错误',
            'sign.required'             => '缺少sign参数',
            'sign_type.required'        => '缺少sign_type参数',
            'in.required'               => 'sign_type参数错误',
        ];
    }
}
